﻿using AutoMapper;
using InventoryIssue.API.Write.Application.Command.Reportloss;
using InventoryIssue.Domain;
using InventoryIssue.ErrorCode;
using InventoryIssue.Infrastructrue.Implement;
using MediatR;

namespace InventoryIssue.API.Write.Application.Handler.Reportloss
{
    public class CreateReportlossHandler : IRequestHandler<CreateReportlossCommand, APIResult<int>>
    {
        private readonly DatabaseContext db;
        private readonly IMapper mapper;

        public CreateReportlossHandler(DatabaseContext db,IMapper mapper)
        {
            this.db = db;
            this.mapper = mapper;
        }
        public async Task<APIResult<int>> Handle(CreateReportlossCommand request, CancellationToken cancellationToken)
        {
            APIResult<int> result = new APIResult<int>();
            
            if (request.Products == null || !request.Products.Any())
            {
                result.Message = "产品列表不能为空";
                result.Code = APIEnum.Fail;
                return result;
            }
            await db.SqlSugar.Ado.BeginTranAsync();
            
            var mainModel = mapper.Map<ReportlossModel>(request);
            await db.SqlSugar.Insertable(mainModel).ExecuteCommandAsync();
            
            var reportlossProductModel = request.Products
                .Select(code => new ReportlossProductModel
                {
                    ReportlossId = request.ReportlossId,
                    ProductId = code.ProductId,
                    Quantity = code.Quantity,
                    CreateTime = DateTime.Now,
                    IsDel = false
                })
                .ToList();

            var insertCount = await db.SqlSugar
                .Insertable(reportlossProductModel) 
                .ExecuteCommandAsync(); 
            await db.SqlSugar.Ado.CommitTranAsync();
            result.Message = $"成功创建报损单并关联 {insertCount} 个产品";
            result.Code = APIEnum.Ok;
            result.Data = insertCount;
            return result;
        }
    }
}
